package com.automotive.can1939.model;

import java.util.Arrays;

/**
 * CAN帧数据模型
 */
public class CanFrame {
    private int canId;           // CAN ID
    private byte[] data;         // 数据字节
    private int dataLength;      // 数据长度
    private boolean isExtended;  // 是否为扩展帧
    private boolean isRemote;    // 是否为远程帧
    private long timestamp;      // 时间戳
    
    public CanFrame() {
        this.data = new byte[8];
        this.timestamp = System.currentTimeMillis();
    }
    
    public CanFrame(int canId, byte[] data) {
        this.canId = canId;
        this.data = Arrays.copyOf(data, Math.min(data.length, 8));
        this.dataLength = this.data.length;
        this.timestamp = System.currentTimeMillis();
    }
    
    public CanFrame(int canId, byte[] data, boolean isExtended) {
        this(canId, data);
        this.isExtended = isExtended;
    }
    
    // Getters and Setters
    public int getCanId() {
        return canId;
    }
    
    public void setCanId(int canId) {
        this.canId = canId;
    }
    
    public byte[] getData() {
        return data;
    }
    
    public void setData(byte[] data) {
        this.data = Arrays.copyOf(data, Math.min(data.length, 8));
        this.dataLength = this.data.length;
    }
    
    public int getDataLength() {
        return dataLength;
    }
    
    public void setDataLength(int dataLength) {
        this.dataLength = Math.min(dataLength, 8);
    }
    
    public boolean isExtended() {
        return isExtended;
    }
    
    public void setExtended(boolean extended) {
        isExtended = extended;
    }
    
    public boolean isRemote() {
        return isRemote;
    }
    
    public void setRemote(boolean remote) {
        isRemote = remote;
    }
    
    public long getTimestamp() {
        return timestamp;
    }
    
    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }
    
    /**
     * 获取数据的十六进制字符串表示
     */
    public String getDataHexString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < dataLength; i++) {
            sb.append(String.format("%02X ", data[i] & 0xFF));
        }
        return sb.toString().trim();
    }
    
    /**
     * 从十六进制字符串设置数据
     */
    public void setDataFromHexString(String hexString) {
        String[] hexBytes = hexString.trim().split("\\s+");
        byte[] newData = new byte[Math.min(hexBytes.length, 8)];
        
        for (int i = 0; i < newData.length; i++) {
            newData[i] = (byte) Integer.parseInt(hexBytes[i], 16);
        }
        
        setData(newData);
    }
    
    @Override
    public String toString() {
        return String.format("CanFrame{ID=0x%X, Data=[%s], Length=%d, Extended=%b, Remote=%b, Time=%d}",
                canId, getDataHexString(), dataLength, isExtended, isRemote, timestamp);
    }
}